package stack;

import java.util.Arrays;
import java.util.EmptyStackException;

//模拟实现栈
public class MyStack {
    private String[] stack;
    private int size;

    public MyStack() {
        stack = new String[1];
        size = 0;
    }
    public MyStack(int capacity) {
        stack = new String[capacity];
        size = 0;
    }
    //扩容
    private void resize(){
      //创建一个更长的数组
        String[] newStack = new String[stack.length*3];
        //将原数组中的元素复制到新数组中
        for(int i=0;i<stack.length;i++){
            newStack[i] = stack[i];
        }
        //更新栈的引用
        stack=newStack;
    }
    //入栈
    public void push(String item){
        if(size==stack.length){
            //kronlei:扩容
            resize();
        }
        stack[size++] = item;
    }
    //出栈
    public String pop(){
        if(size==0){
            throw new EmptyStackException();
        }
        String item = stack[size-1];
        //缩容
        size--;
        return item;
    }
    //获取栈顶元素
    public String peek(){
        if(size==0){
            throw new EmptyStackException();
        }
        // 直接取最后一个元素
        return stack[size-1];
    }

    @Override
    public String toString() {
        return "MyStack{" +
                "stack=" + Arrays.toString(stack) +
                ", size=" + size +
                '}';
    }

    public static void main(String[] args) {
        MyStack stack = new MyStack();
        stack.push("a");
        stack.push("b");
        stack.push("c");
        System.out.println(stack.toString());//MyStack{stack=[a, b, c], size=3}
        System.out.println(stack.peek());//c
        System.out.println(stack.pop());//c
    }

}

